<template>
  <div class="tags-view-container">
    <ScrollPane
      ref="scrollPaneRef"
      class="tags-view-wrapper"
      @scroll="state.handleScroll"
    >
      <router-link
        v-for="tag in visitedStoreViews"
        ref="tag"
        :key="tag.path"
        :class="state.isActive(tag) ? 'active' : ''"
        :to="{path: tag.path, query: tag.query, fullPath: tag.fullPath}"
        tag="span"
        class="tags-view-item"
      >
        {{ tag.meta.title }}
        <span
          v-if="!state.isAffix(tag)"
          class="el-icon-close"
          @click.prevent.stop="state.closeSelectedTag(tag)"
        />
      </router-link>
    </ScrollPane>
  </div>
</template>
<script lang='ts' setup>
  import path from 'path';
  import { RouteRecordRaw, useRoute, useRouter } from 'vue-router';
  import ScrollPane from './ScrollPane.vue'
  import { usePermissionStore } from '@/store/modules/permission'
  import { settingStore } from '@/store/modules/setting'
  import { computed, onBeforeMount, reactive, watch } from 'vue';
  import { TagView } from '#/setting'

  const currentRoute = useRoute()
  const router = useRouter()
  
  const state = reactive({
    visible: false,
    affixTags: [] as TagView[],
    isActive: (route: TagView) => {
      return route.path === currentRoute.path
    },
    isAffix: (tag: TagView) => {
      return tag.meta && tag.meta.affix
    },
    closeSelectedTag: (view: TagView) => {
      settingStore().DEL_VISITED_VIEW(view)
      if (state.isActive(view)) {
        toLastView(visitedStoreViews, view)
      }
    },
    handleScroll: () => {
      console.log('handleScroll');
    }
  })

  /**
   * 关闭当前tag时，默认跳转到上一个router
   * @param visitedViews 
   * @param view 
   */
  const toLastView = (visitedViews: any, view: TagView) => {

    const latestView = visitedViews.value.length > 1 ? visitedViews.value.slice(-1)[0] : visitedViews[0]

    if (latestView !== undefined && latestView.fullPath !== undefined) {
      router.push(latestView.fullPath).catch(err => {
        console.warn(err)
      })
    } else {
      // 如果没有标记视图，则默认重定向到主页，如果您想重新加载主页，请调整它
      if (view.name === 'dashboard') {
        router.push({ path: '/redirect' + view.fullPath }).catch(err => {
          console.warn(err)
        })
      } else {
        router.push('/').catch(err => {
          console.warn(err)
        })
      }
    }
  }

  /**
   * 筛选出查看当前路由含有affix的标签
   * @param routes 
   * @param basePath 
   */
  const filterAffixTags = (routes: RouteRecordRaw[], basePath = '/') => {
    let tags: TagView[] = []

    routes.forEach(route => {
      if (route.meta && route.meta.affix) {
        const tagPath = path.resolve(basePath, route.path)
        tags.push({
          fullPath: tagPath,
          path: tagPath,
          name: route.name,
          meta: { ...route.meta }
        })
      }

      if (route.children) {
        const childTags = filterAffixTags(route.children, route.path)
        if (childTags.length >= 1) {
          tags = tags.concat(childTags)
        }
      }
    })
    return tags
  }

  const initTags = () => {
    state.affixTags = filterAffixTags(routes.value)
    for (const tag of state.affixTags) {
      // Must have tag name
      if (tag.name) {
        settingStore().ADD_VISITED_VIEW(tag)
      }
    }
  }

  const addTags = () => {
    if (currentRoute.name) {
      settingStore().ADD_VISITED_VIEW(currentRoute)
    }
    return false
  }

  const routes = computed(() => usePermissionStore().routes)
  const visitedStoreViews = computed(() => settingStore().visitedViews)

  watch(() => currentRoute.name, () => {
    if (currentRoute.name !== 'Login') {
      addTags()
    }
  })


  onBeforeMount(() => {
    initTags()
    addTags()
  })
</script>
<style lang="scss" scoped>

// Reset element css of el-icon-close
.tags-view-wrapper {
  .tags-view-item {
    .el-icon-close {
      width: 16px;
      height: 16px;
      vertical-align: 2px;
      border-radius: 50%;
      text-align: center;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      transform-origin: 100% 50%;

      &:before {
        transform: scale(0.6);
        display: inline-block;
        vertical-align: -3px;
      }

      &:hover {
        background-color: #b4bccc;
        color: #fff;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.tags-view-container {
  height: 34px;
  width: 100%;
  background: #fff;
  border-bottom: 1px solid #eee;

  .tags-view-wrapper {
    .tags-view-item {
      display: inline-block;
      position: relative;
      cursor: pointer;
      height: 26px;
      line-height: 25px;
      border: 1px solid rgba(124,141,181,.3);
      border-radius: 4px;
      color: #495060;
      background: #fff;
      padding: 0 8px;
      font-size: 12px;
      margin-left: 5px;
      margin-top: 4px;
      box-sizing: border-box;

      &:first-of-type {
        margin-left: 15px;
      }

      &:last-of-type {
        margin-right: 15px;
      }

      &.active {
        background-color: #5DDAB4;
        color: #fff;
      }
    }
  }

  .contextmenu {
    margin: 0;
    background: #fff;
    z-index: 3000;
    position: absolute;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 400;
    color: #333;

    li {
      margin: 0;
      padding: 7px 16px;
      cursor: pointer;

      &:hover {
        background: #eee;
      }
    }
  }
}
</style>
